#include "CCmdParser.h"

#include <QFile>
#include <QTextStream>
CCmdParser::CCmdParser(QObject *parent) : QObject(parent)
  ,_isQuit(false)
{
    QtConcurrent::run(this,&CCmdParser::dealRecv);
    connect(this,SIGNAL(sInput(QByteArray)),this,SLOT(onMainThreadRecv(QByteArray)));
}

void CCmdParser::sendError(const QByteArray &msg,const QByteArray& tail)
{
    QTextStream stream(stderr,QIODevice::WriteOnly);
    stream<<msg<<tail;
    stream.flush();
}

void CCmdParser::sendMsg(const QByteArray &msg,const QByteArray&tail)
{
    QTextStream stream(stdout,QIODevice::WriteOnly);
    stream<<msg<<tail;
    stream.flush();
}


void CCmdParser::onMainThreadRecv(const QByteArray &recv)
{
    QByteArray msg=recv.mid(3).trimmed();
    if(msg.startsWith("resize"))
    {
        if(!_app)
        {
            return sendError("[error] context is not create");
        }
        QByteArrayList params=msg.split(' ');
        if(params.size()<3)
        {
            sendError(msg+" less params");
            return;
        }
        int w=params[1].toInt();
        int h=params[2].toInt();
        _app->resize(w,h);
    }
    else if(msg.startsWith("paint"))
    {
        if(!_app)
        {
            return sendError("[error] context is not create");
        }
        _app->render();
        QByteArray buffer;
        QBuffer writer(&buffer);
        writer.open(QBuffer::ReadWrite);
        _app->grabFramebuffer().save(&writer,"png");
        writer.close();
        sendMsg("[image]"+buffer.toHex());
    }
    else if(msg.startsWith("create"))
    {
        if(!_app)
        {
            _app=std::make_shared<Example>();
        }
    }
}


void CCmdParser::dealRecv()
{
    sendError("[normal] recv dealing...");
    QTextStream stream(stdin,QIODevice::ReadOnly);
    QByteArray msg;
    while (true)
    {
        msg=stream.readLine().toUtf8();
        onInternalRecv(msg);
        if(_isQuit)break;
    }
    sendError("[normal] recv end.");
    qApp->exit(0);
}

void CCmdParser::onInternalRecv(const QByteArray &msg)
{
    sendError("[normal]"+msg);
    if(msg.startsWith("quit"))
    {
        _isQuit=true;
    }
    else if(msg.startsWith("app"))
    {
        emit sInput(msg);
    }
}
